package com.koi.job.task;

import cn.hutool.cron.CronUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.koi.common.constants.KoiConstants;
import com.koi.job.service.job.SysJobService;
import com.koi.pojo.system.SysJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.util.List;

/**
 * @author ･ᴗ･
 * @description [DevJobListener-定时任务监听器，系统启动时将定时任务启动]
 */
@Slf4j
@Configuration
public class KoiJobListener implements ApplicationListener<ApplicationStartedEvent>, Ordered {

    @Resource
    private SysJobService sysJobService;

    @SuppressWarnings("ALL")
    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        // 查询状态正常的定时任务 AND 执行策略是立即执行类型的数据，筛选后进行开始定时任务
        LambdaQueryWrapper<SysJob> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysJob::getJobStatus, KoiConstants.ZERO_STRING);
        wrapper.eq(SysJob::getPolicyStatus, KoiConstants.ONE_STRING);
        List<SysJob> jobList = sysJobService.list(wrapper);
        if(CollectionUtils.isNotEmpty(jobList)){
            for (SysJob sysJob : jobList) {
                // 启动定时任务
                sysJobService.resumeJob(sysJob.getJobId());
            }
        }
        // 设置秒级别的启用
        CronUtil.setMatchSecond(true);
        log.info("启动定时器执行器");
        CronUtil.restart();
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

}
